#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

#define MAX_BUF_SIZE 1024

int main(int argc, char *argv[])
{
    int sockfd, port, addrlen, n;
    char buffer[MAX_BUF_SIZE];
    struct sockaddr_in addr;
    if (argc != 3)
    {
        fprintf(stderr, "Useage:%s server_ip server_port\n", argv[0]);
        exit(1);
    }
    //命令行的第三个参数为数据将要发送到的服务器端口号
    if ((port = atoi(argv[2])) < 0)
    {
        fprintf(stderr, "Usage:%s server_ip server_port\n", argv[0]);
        exit(1);
    }
    sockfd = socket(AF_INET, SOCK_DGRAM, 0); //建立客户端socket
    if (sockfd < 0)
    {
        fprintf(stderr, "Socket Error:%s\n", strerror(errno));
        exit(1);
    }
    addrlen = sizeof(struct sockaddr_in);
    bzero(&addr, addrlen);
    // 客户端填充sockaddr结构
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    //命令行的第三个参数为数据将要发送到的服务器IP地址
    if (inet_aton(argv[1], &addr.sin_addr) < 0)
    {
        fprintf(stderr, "Ip error:%s\n", strerror(errno));
        exit(1);
    }
    //从键盘读入，发送到服务器端
    while (1)
    {
        bzero(buffer, MAX_BUF_SIZE); //接收数据之前先将缓冲区清零
        fgets(buffer, MAX_BUF_SIZE, stdin);
        sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), addrlen);
        printf("Client endpoint input message: %s", buffer);
        //从网络中读取数据，并打印接收到的数据
        n = recvfrom(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)(&addr), &addrlen);
        fprintf(stdout, "Receive message from server: %s", buffer);
    }
    close(sockfd); //通信结束，关闭套接口
    exit(0);
}